package com.htjc.integral.account.util;

import com.htjc.cht.api.util.DigitalSignTool;

import lombok.extern.slf4j.Slf4j;

/**
 * 签名验签工具类
 * @author hlc
 *
 */
@Slf4j(topic = "jfLog")
public class SignUtil {
	
	private static DigitalSignTool signerTool = null;
	private static DigitalSignTool checkSignerTool = null;
	
	static {
		try {
			String path = java.net.URLDecoder.decode(System.getProperty("user.dir"), "utf-8");// 证书路径
			String pfx_file = path + "/sign/dzfp.pfx"; // 商户证书路径
			String keyStorePassword = "000000";// 商户证书库密码
			String keyPassword = "000000";// 商户证书库私钥保护密码
			String rootCertificatePath = path + "/sign/dzfp.pem";
			signerTool = DigitalSignTool.getSigner(pfx_file, keyStorePassword,keyPassword); // 签名工具实例
			checkSignerTool = DigitalSignTool.getVerifier(rootCertificatePath);
		} catch (Exception e) {
			throw new RuntimeException("网关证书服务异常，请联系管理员",e);
		}
	}
	
	/**
	*  数据签名（加签）
	*  @param orginalData待签名数据
	*  @return 成功返回：签名数据；失败返回：null
	*/
	public static String sign(String orginalData) {
		String signData = null;
		try {
			signData = signerTool.sign(orginalData.getBytes());
		}  catch (Exception e) {
			log.error("签名失败"+e.getMessage(),e);
		}
		return signData;
	}

	
	/**
	 * 数据验证（验签）
	 * @param signature
     * @param data
     * @param dn
     * @return
     */
	public static boolean verify(String signature, byte[] data) {
        try {
        	checkSignerTool.verify(signature, data, null);
            return true;
        } catch (Exception e) {
        	log.error("验签失败"+e.getMessage(),e);
        	return false;
        }
    }
	

}
